import mqtt from '../../utils/mqtt.js';
const aliyunOpt = require('../../utils/aliyun/aliyun_connect.js')

Page({
  data:{
    ImgSrc:"",
    AliyunDeviceInfo:{
      ProductKey:"h2jdf7ltZqq",
      DeviceName: "M_wx_camcar",
      DeviceSecret:"caa7ad6f4eb30ab0cbdba702def388ef",
      regionId: 'cn-shanghai', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
      up_raw:'/h2jdf7ltZqq/M_wx_camcar/user/RecvJpeg'
    },
    client: null,
    //记录重连的次数
    reconnectCounts: 0,
    //MQTT连接的配置
    options: {
      protocolVersion: 4, //MQTT连接协议版本
      clean: false,
      reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
      connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
      resubscribe: true, //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
      clientId: '',
      password: '',
      username: '',
    },
  },
  ConnectAliyunServer(e){
    var that = this
    //传进去三元组等信息，拿到mqtt连接的各个参数
    let clientOpt = aliyunOpt.getAliyunIotMqttClient({
      productKey: that.data.AliyunDeviceInfo.ProductKey,
      deviceName: that.data.AliyunDeviceInfo.DeviceName,
      deviceSecret: that.data.AliyunDeviceInfo.DeviceSecret,
      regionId: that.data.AliyunDeviceInfo.regionId,
      port: that.data.AliyunDeviceInfo.port,
    });
    //console.log("get data:" + JSON.stringify(clientOpt));
    //得到连接域名
    let host = 'wxs://'+clientOpt.host;
    this.setData({
      'options.clientId': clientOpt.clientId,
      'options.password': clientOpt.password,
      'options.username': clientOpt.username,
    })
    //console.log("this.data.options host:" + host);
    //console.log("this.data.options data:" + JSON.stringify(this.data.options));
    //开始连接
    this.data.client = mqtt.connect(host, this.data.options);
    this.data.client.on('connect', function(connack) {
      wx.showToast({
        title: '连接成功'
      })
    })
    that.data.client.on("message", function(topic, payload) {
      var len = payload.length
      console.log(len)
      if((payload[1] == 0xd8)){
        if(payload[len - 1] == 0xd9){
          that.JpegReady(payload)
        }
      }
      // wx.showModal({
      //   content: " 收到topic:[" + topic + "], payload :[" + payload + "]",
      //   showCancel: false,
      // });
    })
    //服务器连接异常的回调
    that.data.client.on("error", function(error) {
      console.log(" 服务器 error 的回调" + error)
    })
    //服务器重连连接异常的回调
    that.data.client.on("reconnect", function() {
      console.log(" 服务器 reconnect的回调")

    })
    //服务器连接异常的回调
    that.data.client.on("offline", function(errr) {
      console.log(" 服务器offline的回调")
    })
  },
  SubTopic: function() {
    if (this.data.client && this.data.client.connected) {
      //仅订阅单个主题
      this.data.client.subscribe('/h2jdf7ltZqq/M_wx_camcar/user/RecvJpeg', function(err, granted) {
        if (!err) {
          console.log("订阅主题成功")
          wx.showToast({
            title: '订阅主题成功'
          })
        } else {
          console.log("订阅主题失败")
          wx.showToast({
            title: '订阅主题失败',
            icon: 'fail',
            duration: 2000
          })
        }
      })
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  SendData(e){
    if (this.data.client && this.data.client.connected) {
      var sendData = {Data:"Hello, I'm wx camcar"}
      this.data.client.publish(this.data.AliyunDeviceInfo.up_raw, JSON.stringify(sendData));
      console.log("send ok")
    }
    else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  JpegReady:function(data){
    //da = null
    var base641 = wx.arrayBufferToBase64(data)
    this.setData({
      ImgSrc:'data:image/png;base64,'+base641
    })
    console.log("ok")
  },
  onReady:function(options){
    this.ConnectAliyunServer()
    //this.JpegReady()
  }

})